package com.luanhj.system.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.luanhj.common.core.domain.entity.SysUser;
import com.luanhj.common.core.domain.entity.Tenant;
import com.luanhj.common.core.domain.entity.TenantFile;
import com.luanhj.common.utils.DateUtils;
import com.luanhj.common.utils.SecurityUtils;
import com.luanhj.common.utils.StringUtils;
import com.luanhj.common.utils.bean.BeanUtils;
import com.luanhj.system.domain.SysStudent;
import com.luanhj.system.domain.SysUserPost;
import com.luanhj.system.domain.SysUserRole;
import com.luanhj.system.domain.dto.TenantDTO;
import com.luanhj.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.luanhj.system.service.ITenantService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 租户Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-03
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserNoTenantMapper userNoTenantMapper;


    @Autowired
    private TenantNoTenantMapper tenantNoTenantMapper;

    @Autowired
    private TenantFileMapper tenantFileMapper;

    @Value(value = "${ruoyi.default.user.password}")
    private String defaultPassword;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<Tenant> queryList(Tenant tenant) {
        // 注意：mybatis-plus lambda 模式不支持 eclipse 的编译器
        // LambdaQueryWrapper<SysStudent> queryWrapper = Wrappers.lambdaQuery();
        // queryWrapper.eq(SysStudent::getStudentName, sysStudent.getStudentName());
        QueryWrapper<Tenant> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(tenant.getName())) {
            queryWrapper.eq("name", tenant.getName());
        }
        if (StringUtils.isNotNull(tenant.getContactEmail())) {
            queryWrapper.eq("contact_email", tenant.getContactEmail());
        }
        if (StringUtils.isNotEmpty(tenant.getContactPhone())) {
            queryWrapper.eq("contact_phone", tenant.getContactPhone());
        }
        if (StringUtils.isNotNull(tenant.getStatus())) {
            queryWrapper.eq("status", tenant.getStatus());
        }
        if (StringUtils.isNotEmpty(tenant.getRemark())) {
            queryWrapper.eq("remark", tenant.getRemark());
        }
        if (StringUtils.isNotEmpty(tenant.getRemark())) {
            queryWrapper.eq("remark", tenant.getRemark());
        }
        return this.list(queryWrapper);
    }

    /**
     * 查询租户人数
     *
     * @return
     */
    @Override
    public Map<String, Integer> countUsersPerTenant() {
        String sql = "SELECT tenant_id, COUNT(*) as count FROM sys_user GROUP BY tenant_id";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        Map<String, Integer> stats = new HashMap<>();
        for (Map<String, Object> row : result) {
            String tenantId = (String) row.get("tenant_id");
            Integer count = ((Number) row.get("count")).intValue();
            stats.put(tenantId, count);
        }
        return stats;
    }

    @Override
    public int updateTenantStatus(Tenant tenant) {
        Tenant model = tenantMapper.selectById(tenant.getId());
        model.setStatus(tenant.getStatus());
        return tenantMapper.updateById(model);
    }


    /*********************************以下是NoTenant**********************************/

    @Override
    public List<TenantDTO> noTenantQueryList(Tenant tenant) {
        MPJLambdaWrapper<Tenant> wrapper = new MPJLambdaWrapper<Tenant>()
                .selectAll(Tenant.class)//查询user表全部字段
                .selectAs(SysUser::getUserName, TenantDTO::getInitialAdminUserName)
                .selectAs(SysUser::getNickName, TenantDTO::getInitialAdminNickName)
                .leftJoin(SysUser.class, SysUser::getUserId, Tenant::getInitialAdminId);
        // 添加查询条件
        if (StringUtils.isNotBlank(tenant.getName())) {
            wrapper.like(Tenant::getName, tenant.getName());
        }
        if (tenant.getStatus() != null) {
            wrapper.eq(Tenant::getStatus, tenant.getStatus());
        }
        if (StringUtils.isNotBlank(tenant.getContactPhone())) {
            wrapper.eq(Tenant::getContactPhone, tenant.getContactPhone());
        }
        List<TenantDTO> list = tenantNoTenantMapper.selectJoinList(TenantDTO.class, wrapper);
        return list;
    }

    @Override
    public TenantDTO getInfo(String id) {

        TenantDTO info = new TenantDTO();
        MPJLambdaWrapper<Tenant> wrapper = new MPJLambdaWrapper<Tenant>()
                .selectAll(Tenant.class)
                .select(SysUser::getNickName)
                .selectAs(SysUser::getUserName, TenantDTO::getInitialAdminUserName)
                .select(SysUser::getUserName)
                .select(SysUser::getPassword)
                .select(SysUser::getUserId)

                .leftJoin(SysUser.class, SysUser::getUserId, Tenant::getInitialAdminId)
                .eq(Tenant::getId, id);
        info = tenantNoTenantMapper.selectJoinOne(TenantDTO.class, wrapper);
        return info;
    }

    @Transactional
    @Override
    public int createTenant(TenantDTO tenantDTO) {
        // 保存租户信息
        Tenant tenant = new Tenant();
        BeanUtils.copyBeanProp(tenant, tenantDTO);
        this.save(tenant);
        // 保存初始化管理员信息
        SysUser sysUser = new SysUser();
        sysUser.setTenantId(tenant.getId());
        //sysUser.setPwdUpdateDate(DateUtils.getNowDate());
        if (tenantDTO.isInitialAuto()) {
            sysUser.setPassword(SecurityUtils.encryptPassword(defaultPassword));
            sysUser.setUserName(tenantDTO.getName());
            sysUser.setNickName(tenantDTO.getName());
        } else {
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
            sysUser.setUserName(tenantDTO.getUserName());
            sysUser.setNickName(tenantDTO.getNickName());
        }

        sysUser.setStatus("0");
        sysUser.setCreateTime(DateUtils.getNowDate());
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setDelFlag("0");
        userNoTenantMapper.insert(sysUser);

        // 赋予管理员角色
        insertUserRole(sysUser.getUserId(), new Long[]{100L});

        tenant.setInitialAdminId(sysUser.getUserId());
        // 更新租户信息
        this.updateById(tenant);
        // 保存租户文件资料
        for (TenantFile tenantFile : tenantDTO.getFiles()) {
            tenantFile.setTenantId(tenant.getId());
            tenantFile.setCreateTime(DateUtils.getNowDate());
            tenantFile.setCreateBy(SecurityUtils.getUsername());
            tenantFileMapper.insert(tenantFile);
        }

        return 1;
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            sysUserPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            sysUserRoleMapper.batchUserRole(list);
        }
    }
}
